package algorithm.leetcode;

import java.util.Stack;

/**
 * 括号匹配
 * stack操作
 * push 放
 * peek 只看，不取
 * pop 取栈顶
 */
public class KHMatch {

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for(int i=0; i<s.length(); i++) {
            Character ch = s.charAt(i);
            if(isLeft(ch)) {
                stack.push(ch);
                continue;
            }

            if(isRight(ch) && stack.isEmpty()) {
                return false;
            }
            if(isRight(ch)  && match(stack.peek(), ch)) {
                stack.pop();
            } else {
                return false;
            }

        }

        if(stack.isEmpty() ) {
            return true;
        }
        return false;

    }

    public boolean match(Character source, Character test) {
        if('(' == source && ')' == test) {
            return true;
        } else if('[' == source && ']' == test) {
            return true;
        } else if('{' == source && '}' == test) {
            return true;
        }
        return false;
    }

    public boolean isLeft(Character c) {
        if('(' == c || '[' == c || '{' == c) {
            return true;
        }
        return false;
    }

    public boolean isRight(Character c) {
        if(')' == c || ']' == c || '}' == c) {
            return true;
        }
        return false;
    }

    public static void main(String [] args) {
        System.out.println(new KHMatch().isValid("()"));
    }
}
